package model

import (
	"database/sql"
	"log"
)

// History represents the history table in the database.
type History struct {
	ID            uint64   `json:"id" db:"id"`                           // Primary key
	StockNo       string   `json:"stock_no" db:"stock_no"`               // 股票编号
	Name          string   `json:"name" db:"name"`                       // 股票名称
	OpenPrice     float64  `json:"open_price" db:"open_price"`           // 开盘价格
	OpenBfqPrice  float64  `json:"open_bfq_price" db:"open_bfq_price"`   // 开盘价格 不复权
	ClosePrice    float64  `json:"close_price" db:"close_price"`         // 收盘价格
	CloseBfqPrice float64  `json:"close_bfq_price" db:"close_bfq_price"` // 不复权的收盘价
	DiffRate      float64  `json:"diff_rate" db:"diff_rate"`             // 涨跌幅度
	MaxPrice      *float64 `json:"max_price" db:"max_price"`             // 最高价
	MaxBfqPrice   float64  `json:"max_bfq_price" db:"max_bfq_price"`     // 不复权的最高价
	MinPrice      *float64 `json:"min_price" db:"min_price"`             // 最低价
	MinBfqPrice   float64  `json:"min_bfq_price" db:"min_bfq_price"`     // 不复权的最低价
	TurnoverRate  *float64 `json:"turnover_rate" db:"turnover_rate"`     // 换手率（百分比）
	StaticPE      float64  `json:"static_pe" db:"static_pe"`             // 静态市盈率
	PE            float64  `json:"pe" db:"pe"`                           // 动态市盈率
	TTM           float64  `json:"ttm" db:"ttm"`                         // 市盈率TTM
	Volumn        *float64 `json:"volumn" db:"volumn"`                   // 成交数
	TradeAmount   *float64 `json:"trade_amount" db:"trade_amount"`       // 成交额（元）
	LimitUp       bool     `json:"limit_up" db:"limit_up"`               // 是否涨停，1涨停，0不是
	LimitDown     bool     `json:"limit_down" db:"limit_down"`           // 是否跌停，1跌停，0不是
	SmallOrder    float64  `json:"small_order" db:"small_order"`         // 小单金额
	MiddleOrder   float64  `json:"middle_order" db:"middle_order"`       // 中单金额
	BigOrder      float64  `json:"big_order" db:"big_order"`             // 大单金额
	LargeOrder    float64  `json:"large_order" db:"large_order"`         // 特大单金额
	Date          string   `json:"date" db:"date"`                       // 日期
}

// Save method to insert or update a stock record in the database
func (s *History) Save() error {
	// Check if the stock with the same stock_code exists in the database
	var count int
	err := db.QueryRow("SELECT COUNT(*) FROM history WHERE stock_code = ? AND date = ?", s.StockNo, s.Date).Scan(&count)
	if err != nil {
		log.Printf("Failed to check if stock exists: %v", err)
		return err
	}

	// Prepare query based on whether the stock exists
	var query string
	if count > 0 {
		query = `
			UPDATE history
			SET name = ?, open_price = ?, open_bfq_price = ?, close_price = ?, close_bfq_price = ?, 
			diff_rate = ?, max_price = ?, max_bfq_price = ?, min_price = ?, min_bfq_price = ?, turnover_rate = ?,
			static_pe = ?, pe = ?, ttm = ?, volumn = ?, trade_amount = ?, limit_up = ?,
			limit_down = ?, small_order = ?, middle_order = ?, big_order = ?, large_order = ?
			WHERE stock_no = ? AND date = ?
		`
	} else {
		query = `
			INSERT INTO history 
			(stock_no, name, open_price, open_bfq_price, close_price, close_bfq_price, diff_rate, 
			max_price, max_bfq_price, min_price, min_bfq_price, turnover_rate, static_pe, pe, 
			ttm, volumn, trade_amount, limit_up, limit_down, small_order, middle_order, 
			big_order, large_order, date) 
			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		`
	}

	// Execute the query
	var res sql.Result
	if count > 0 {
		res, err = db.Exec(query, s.Name, s.OpenPrice, s.OpenBfqPrice, s.ClosePrice, s.CloseBfqPrice,
			s.DiffRate, s.MaxPrice, s.MaxBfqPrice, s.MinPrice, s.MaxBfqPrice, s.TurnoverRate,
			s.StaticPE, s.PE, s.TTM, s.Volumn, s.TradeAmount, s.LimitUp,
			s.LimitDown, s.SmallOrder, s.MiddleOrder, s.BigOrder, s.LargeOrder, s.StockNo, s.Date)
	} else {
		res, err = db.Exec(query, s.StockNo, s.Name, s.OpenPrice, s.OpenBfqPrice, s.ClosePrice, s.CloseBfqPrice,
			s.DiffRate, s.MaxPrice, s.MaxBfqPrice, s.MinPrice, s.MaxBfqPrice, s.TurnoverRate,
			s.StaticPE, s.PE, s.TTM, s.Volumn, s.TradeAmount, s.LimitUp,
			s.LimitDown, s.SmallOrder, s.MiddleOrder, s.BigOrder, s.LargeOrder, s.Date)
	}
	if err != nil {
		log.Printf("Error saving stock: %v", err)
		return err
	}

	// Check the number of rows affected to determine if it was an update or insert
	rowsAffected, err := res.RowsAffected()
	if err != nil {
		log.Printf("Error getting rows affected: %v", err)
		return err
	}
	if count > 0 && rowsAffected > 0 {
		// log.Printf("Stock with stock_code %s updated successfully", s.StockCode)
	} else if rowsAffected > 0 {
		// log.Printf("Stock with stock_code %s inserted successfully", s.StockCode)
	}

	return nil
}
